import Vue from 'vue'
import VueRouter from 'vue-router'
import { Message } from 'element-ui';

Vue.use(VueRouter)
//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
    console.log(this,location)
   // 调用原来的push函数，并捕获异常 call=>显示改变this执向
    //this：路由实例   
    //location：跳转的path路径 
   return originalPush.call(this, location).catch(err => err)
}


const routes = [
    {
        path: '/login',
        component: () => import('../views/login/Login.vue')
    },
    {
        path: '/',
        component: () => import('../views/index/Index.vue'),
        children: [
            {
                path: "home",
                meta:{title:"基本设置"},//路由元信息
                component:()=>import("../views/home/Home.vue")
            },
            {
                path: "menu",
                meta:{title:"菜单管理"},//路由元信息
                component:()=>import("../views/menu/Menu.vue")
            },
            {
                path: "role",
                meta:{title:"角色管理"},//路由元信息
                component:()=>import("../views/role/Role.vue")
            },
            {
                path: "user",
                meta:{title:"管理员管理"},//路由元信息
                component:()=>import("../views/user/User.vue")
            },
            {
                path:"category",
                meta:{title:"商品分类管理"},
                component:()=>import("../views/cate/Cate.vue")
            },
            {
                path:'/specs',
                meta:{title:"商品规格管理"},
                component:()=>import("../views/specs/Specs.vue")
            },
            {
                path:'/goods',
                meta:{title:"商品列表"},
                component:()=>import("../views/goods/Good.vue")
            },
            {
                path:"/",
                redirect:"home"
            }
        ]

    },
]

const router = new VueRouter({
    routes
})

export default router


//定义全局前置路由守卫

router.beforeEach((to,from,next)=>{
    //1.进行检测登录
    let userInfo = localStorage.getItem('userInfo') ||""
    // 2.检测用户是否登录？登录后检测访问地址是否合法？
    if(userInfo ==""){
        ////2.1用户没有登陆 检测是否去登录
        to.path == "/login" ? next() : next('/login')
    }else{
        // 2.2用户登录检测权限是否合法 检测用户访问的功能地址（/home..）是否合法
        let userPath = JSON.parse(userInfo).menus_url
        userPath = [...userPath,'/home']
        if(!userPath.includes(to.path)){
            Message({message: '权限不合法，请合理使用！',type: 'warning'})
            next("/")
        }else{
            next()
        }

    }
    // if(userInfo==""&&to.path!="/login"){
    //     //2.检测没有登录信息切访问页面不是登录页 就强制跳转到登录页
    //     next('login')
    // }else{
    //     next()
    // }
})


